package com.foogui.guava;

import com.github.rholder.retry.*;
import org.junit.Test;

import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class RetryDemo {
    public int realAction(int num) {
        int judge = new Random().nextInt(10);
        if (judge <= 5) {
            throw new IllegalArgumentException();
        }
        return num;
    }
    @Test
    public void retry() throws ExecutionException, RetryException {
        int num=1;
        Retryer<Integer> retry = RetryerBuilder.<Integer>newBuilder()
                .retryIfException()
                // 重试监听器
                .withRetryListener(new MyRetryListener())
                // 设置重试等待策略
                .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
                // 停止策略
                .withStopStrategy(StopStrategies.stopAfterAttempt(10))
                .build();
        Integer result = retry.call(() -> realAction(realAction(num)));
        System.out.println("返回的结果是"+result);

    }

    private static class MyRetryListener implements RetryListener {

        @Override
        public <V> void onRetry(Attempt<V> attempt) {
            System.out.println("第" + attempt.getAttemptNumber() + "次执行");
        }
    }
}
